// 增强关卡系统 - 程序化生成与肉鸽整合
class LevelManagerEnhanced extends LevelManager {
    constructor() {
        super();
        this.proceduralGenerator = null;
        this.currentLevelVariant = null;
        this.levelModifierSystem = new LevelModifierSystem();
        this.dynamicEnvironment = new DynamicEnvironmentSystem();
        
        // 确保肉鸽增强系统可用
        if (window.roguelikeEnhanced) {
            this.proceduralGenerator = window.roguelikeEnhanced.levelGenerator;
        }
    }
    
    // 重写 startLevel 方法以支持程序化生成
    startLevel(levelNumber) {
        try {
            console.log(`🎯 启动增强关卡 ${levelNumber}`);
            
            // 调用父类的基础设置
            super.startLevel(levelNumber);
            
            // 生成程序化关卡变体
            this.generateLevelVariant(levelNumber);
            
            // 应用关卡修饰符
            this.applyLevelModifiers();
            
            // 设置动态环境
            this.setupDynamicEnvironment();
            
            // 应用肉鸽增强效果
            this.applyRoguelikeEnhancements();
            
            console.log(`✅ 增强关卡 ${levelNumber} 启动成功`);
            
        } catch (error) {
            console.error('增强关卡启动失败:', error);
            throw error;
        }
    }
    
    // 生成关卡变体
    generateLevelVariant(levelNumber) {
        if (!this.proceduralGenerator) {
            console.warn('程序化生成器未可用，使用默认关卡');
            return;
        }
        
        try {
            const baseLevelData = this.levels[levelNumber - 1];
            this.currentLevelVariant = this.proceduralGenerator.generateLevelVariant(levelNumber - 1);
            this.currentLevelVariant = this.proceduralGenerator.applyRandomModifiers(this.currentLevelVariant);
            
            // 将变体数据应用到当前关卡
            this.applyVariantToLevel(baseLevelData, this.currentLevelVariant);
            
            console.log(`🎲 生成关卡变体: ${this.currentLevelVariant.variant}`, this.currentLevelVariant);
            
        } catch (error) {
            console.error('生成关卡变体失败:', error);
        }
    }
    
    // 将变体数据应用到关卡
    applyVariantToLevel(baseLevelData, variant) {
        if (!variant || !baseLevelData) return;
        
        // 应用修饰符到关卡数据
        variant.modifiers.forEach(modifier => {
            this.applyModifierToLevel(baseLevelData, modifier);
        });
        
        // 更新UI显示变体信息
        this.updateVariantUI(variant);
    }
    
    applyModifierToLevel(levelData, modifier) {
        const effects = modifier.effect;
        
        Object.entries(effects).forEach(([key, value]) => {
            switch (key) {
                case 'zombieCount':
                    levelData.zombieCount = Math.floor(levelData.zombieCount * value);
                    break;
                case 'spawnRate':
                    if (this.zombieSpawner) {
                        this.zombieSpawner.spawnRate *= value;
                    }
                    break;
                case 'zombieHealth':
                    // 这将在僵尸生成时应用
                    levelData.zombieHealthMultiplier = value;
                    break;
                case 'zombieSpeed':
                    levelData.zombieSpeedMultiplier = value;
                    break;
                case 'timeLimit':
                    levelData.timeLimit = Math.floor(levelData.timeLimit * value);
                    break;
                case 'scoreMultiplier':
                    levelData.scoreMultiplier = value;
                    break;
            }
        });
        
        console.log(`📊 应用修饰符: ${modifier.name}`, effects);
    }
    
    // 更新变体UI显示
    updateVariantUI(variant) {
        // 在关卡信息中显示变体名称和修饰符
        const levelInfoElement = document.getElementById('currentLevel');
        if (levelInfoElement && variant.variant) {
            levelInfoElement.textContent = `${this.currentLevel} - ${variant.variant}`;
        }
        
        // 显示修饰符效果
        this.showModifierEffects(variant.modifiers);
    }
    
    showModifierEffects(modifiers) {
        if (!modifiers || modifiers.length === 0) return;
        
        // 创建修饰符显示UI
        let modifierDisplay = document.getElementById('levelModifiers');
        if (!modifierDisplay) {
            modifierDisplay = document.createElement('div');
            modifierDisplay.id = 'levelModifiers';
            modifierDisplay.className = 'level-modifiers';
            
            const gameUI = document.getElementById('gameUI');
            if (gameUI) {
                gameUI.appendChild(modifierDisplay);
            }
        }
        
        modifierDisplay.innerHTML = modifiers.map(modifier => `
            <div class="modifier-badge" title="${modifier.description}">
                <span class="modifier-name">${modifier.name}</span>
            </div>
        `).join('');
        
        // 添加样式
        this.addModifierStyles();
        
        // 5秒后隐藏
        setTimeout(() => {
            if (modifierDisplay) {
                modifierDisplay.style.opacity = '0';
                setTimeout(() => {
                    modifierDisplay.style.display = 'none';
                }, 500);
            }
        }, 5000);
    }
    
    // 应用关卡修饰符
    applyLevelModifiers() {
        if (!this.currentLevelVariant || !this.currentLevelVariant.modifiers) return;
        
        this.currentLevelVariant.modifiers.forEach(modifier => {
            this.levelModifierSystem.applyModifier(modifier);
        });
    }
    
    // 设置动态环境
    setupDynamicEnvironment() {
        if (!this.currentLevelVariant || !this.currentLevelVariant.proceduralElements) return;
        
        const elements = this.currentLevelVariant.proceduralElements;
        
        // 设置特殊区域
        if (elements.specialZones) {
            elements.specialZones.forEach(zone => {
                this.dynamicEnvironment.createSpecialZone(zone);
            });
        }
        
        // 设置障碍物
        if (elements.obstacles) {
            elements.obstacles.forEach(obstacle => {
                this.dynamicEnvironment.createObstacle(obstacle);
            });
        }
        
        // 设置动态道具生成点
        if (elements.itemLocations) {
            this.setupProceduralItems(elements.itemLocations);
        }
    }
    
    setupProceduralItems(itemLocations) {
        itemLocations.forEach(location => {
            setTimeout(() => {
                this.spawnProceduralItem(location);
            }, Math.random() * 10000); // 随机延迟生成
        });
    }
    
    spawnProceduralItem(location) {
        if (!window.gameEngine) return;
        
        const itemType = this.selectItemByRarity(location.rarity);
        
        switch (location.type) {
            case 'ammo':
                this.spawnAmmoPickup(location.x, location.y);
                break;
            case 'health':
                this.spawnHealthPickup(location.x, location.y);
                break;
            case 'weapon':
                this.spawnRandomWeapon(location.x, location.y, location.rarity);
                break;
            case 'powerup':
                this.spawnRandomPowerup(location.x, location.y);
                break;
        }
    }
    
    spawnRandomWeapon(x, y, rarity = 'common') {
        if (!window.roguelikeEnhanced || !window.roguelikeEnhanced.equipmentSystem) return;
        
        // 生成程序化武器
        const baseWeapons = ['pistol', 'rifle', 'shotgun', 'smg'];
        const baseWeapon = baseWeapons[Math.floor(Math.random() * baseWeapons.length)];
        const proceduralWeapon = window.roguelikeEnhanced.equipmentSystem.generateRandomWeapon(
            { name: baseWeapon, damage: 25, fireRate: 500 }, 
            rarity
        );
        
        // 创建武器拾取物
        const weaponPickup = {
            x: x,
            y: y,
            width: 30,
            height: 20,
            type: 'weapon',
            weaponData: proceduralWeapon,
            rarity: rarity
        };
        
        if (window.gameEngine) {
            window.gameEngine.weapons.push(weaponPickup);
        }
        
        console.log(`🔫 生成程序化武器: ${proceduralWeapon.name} (${rarity})`);
    }
    
    // 应用肉鸽增强效果
    applyRoguelikeEnhancements() {
        if (!window.roguelikeEnhanced) return;
        
        // 应用遗产奖励效果
        window.roguelikeEnhanced.applyLegacyBonuses();
        
        // 更新运行统计
        window.roguelikeEnhanced.completeLevel(this.currentLevel);
        
        console.log('🎮 肉鸽增强效果已应用');
    }
    
    // 重写关卡完成处理
    onLevelComplete() {
        // 调用父类方法
        super.onLevelComplete && super.onLevelComplete();
        
        // 肉鸽系统相关处理
        if (window.roguelikeEnhanced) {
            // 更新统计
            window.roguelikeEnhanced.completeLevel(this.currentLevel);
            
            // 奖励金币
            const coinReward = this.calculateCoinReward();
            window.roguelikeSystem && window.roguelikeSystem.addCurrency(coinReward);
            
            // 显示升级选择
            if (this.currentLevel < this.maxLevel && window.roguelikeSystem) {
                setTimeout(() => {
                    window.roguelikeSystem.showUpgradeSelection();
                }, 1000);
            }
        }
    }
    
    calculateCoinReward() {
        let baseReward = 20 + this.currentLevel * 5;
        
        // 根据关卡修饰符调整奖励
        if (this.currentLevelVariant && this.currentLevelVariant.modifiers) {
            this.currentLevelVariant.modifiers.forEach(modifier => {
                if (modifier.effect.scoreMultiplier) {
                    baseReward = Math.floor(baseReward * modifier.effect.scoreMultiplier);
                }
            });
        }
        
        return baseReward;
    }
    
    // 重写玩家死亡处理
    onPlayerDeath() {
        if (window.roguelikeEnhanced) {
            // 更新死亡前的运行数据
            window.roguelikeEnhanced.updateRunStats(
                window.gameEngine ? window.gameEngine.zombies.filter(z => z.isDead).length : 0,
                0
            );
            
            // 处理永久死亡
            window.roguelikeEnhanced.handlePlayerDeath();
        }
    }
    
    selectItemByRarity(rarity) {
        // 根据稀有度选择物品
        const rarityMap = {
            'common': ['ammo', 'health'],
            'rare': ['ammo', 'health', 'powerup'],
            'epic': ['weapon', 'powerup'],
            'legendary': ['weapon']
        };
        
        const items = rarityMap[rarity] || rarityMap.common;
        return items[Math.floor(Math.random() * items.length)];
    }
    
    addModifierStyles() {
        if (document.getElementById('levelModifierStyles')) return;
        
        const styles = document.createElement('style');
        styles.id = 'levelModifierStyles';
        styles.textContent = `
            .level-modifiers {
                position: fixed;
                top: 100px;
                left: 20px;
                z-index: 1000;
                display: flex;
                flex-direction: column;
                gap: 10px;
                transition: opacity 0.5s ease;
            }
            
            .modifier-badge {
                background: linear-gradient(135deg, rgba(155, 89, 182, 0.9), rgba(142, 68, 173, 0.9));
                border: 2px solid #9b59b6;
                border-radius: 12px;
                padding: 8px 12px;
                color: white;
                font-size: 12px;
                font-weight: bold;
                text-shadow: 0 1px 2px rgba(0, 0, 0, 0.8);
                box-shadow: 0 3px 10px rgba(155, 89, 182, 0.3);
                animation: modifierEntry 0.6s ease-out;
            }
            
            .modifier-name {
                text-transform: uppercase;
                letter-spacing: 1px;
            }
            
            @keyframes modifierEntry {
                0% {
                    opacity: 0;
                    transform: translateX(-50px);
                }
                100% {
                    opacity: 1;
                    transform: translateX(0);
                }
            }
        `;
        
        document.head.appendChild(styles);
    }
}

// 关卡修饰符系统
class LevelModifierSystem {
    constructor() {
        this.activeModifiers = [];
    }
    
    applyModifier(modifier) {
        this.activeModifiers.push(modifier);
        
        // 根据修饰符类型执行相应效果
        switch (modifier.name) {
            case 'denseSwarm':
                this.applyDenseSwarm(modifier.effect);
                break;
            case 'eliteForces':
                this.applyEliteForces(modifier.effect);
                break;
            case 'ammunition':
                this.applyAmmunition(modifier.effect);
                break;
            case 'timeAttack':
                this.applyTimeAttack(modifier.effect);
                break;
            case 'darkMode':
                this.applyDarkMode(modifier.effect);
                break;
            case 'berserk':
                this.applyBerserk(modifier.effect);
                break;
        }
        
        console.log(`⚡ 应用关卡修饰符: ${modifier.name}`);
    }
    
    applyDenseSwarm(effect) {
        // 密集群体：增加僵尸数量和生成速度
        if (window.levelManager && window.levelManager.zombieSpawner) {
            const originalRate = window.levelManager.zombieSpawner.spawnRate || 2000;
            window.levelManager.zombieSpawner.spawnRate = originalRate / (effect.spawnRate || 1.3);
        }
    }
    
    applyEliteForces(effect) {
        // 精英部队：增强僵尸属性
        this.zombieHealthMultiplier = effect.zombieHealth || 1.4;
        this.zombieSpeedMultiplier = effect.zombieSpeed || 1.2;
    }
    
    applyAmmunition(effect) {
        // 弹药丰富：增加弹药掉落
        if (window.gameEngine) {
            window.gameEngine.ammoDropRateMultiplier = effect.ammoDropRate || 2.0;
        }
    }
    
    applyTimeAttack(effect) {
        // 时间紧迫：减少时间但增加分数
        this.scoreMultiplier = effect.scoreMultiplier || 1.5;
    }
    
    applyDarkMode(effect) {
        // 黑暗模式：降低可见度
        this.applyVisibilityEffect(effect.visibility || 0.7);
    }
    
    applyBerserk(effect) {
        // 狂暴模式：增强玩家但也增强敌人
        if (window.player) {
            window.player.speed *= (effect.playerSpeed || 1.3);
            if (window.player.currentWeapon) {
                window.player.currentWeapon.damage = Math.floor(
                    window.player.currentWeapon.damage * (effect.playerDamage || 1.2)
                );
            }
        }
        
        this.zombieDamageMultiplier = effect.zombieDamage || 1.3;
    }
    
    applyVisibilityEffect(visibility) {
        // 创建黑暗覆盖层
        const darkOverlay = document.createElement('div');
        darkOverlay.id = 'darkModeOverlay';
        darkOverlay.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: radial-gradient(circle at var(--player-x, 50%) var(--player-y, 50%), 
                transparent 120px, 
                rgba(0, 0, 0, ${1 - visibility}) 200px);
            pointer-events: none;
            z-index: 500;
        `;
        
        document.body.appendChild(darkOverlay);
        
        // 动态更新玩家位置
        if (window.player) {
            const updatePlayerPosition = () => {
                if (window.player && darkOverlay.parentNode) {
                    const canvas = document.getElementById('gameCanvas');
                    if (canvas) {
                        const rect = canvas.getBoundingClientRect();
                        const playerX = ((window.player.x / canvas.width) * 100) + '%';
                        const playerY = ((window.player.y / canvas.height) * 100) + '%';
                        
                        darkOverlay.style.setProperty('--player-x', playerX);
                        darkOverlay.style.setProperty('--player-y', playerY);
                    }
                    requestAnimationFrame(updatePlayerPosition);
                }
            };
            updatePlayerPosition();
        }
    }
    
    // 获取当前生效的修饰符效果
    getZombieModifiers() {
        return {
            healthMultiplier: this.zombieHealthMultiplier || 1,
            speedMultiplier: this.zombieSpeedMultiplier || 1,
            damageMultiplier: this.zombieDamageMultiplier || 1
        };
    }
    
    clearModifiers() {
        this.activeModifiers = [];
        this.zombieHealthMultiplier = 1;
        this.zombieSpeedMultiplier = 1;
        this.zombieDamageMultiplier = 1;
        this.scoreMultiplier = 1;
        
        // 清理黑暗模式覆盖层
        const darkOverlay = document.getElementById('darkModeOverlay');
        if (darkOverlay && darkOverlay.parentNode) {
            document.body.removeChild(darkOverlay);
        }
    }
}

// 动态环境系统
class DynamicEnvironmentSystem {
    constructor() {
        this.specialZones = [];
        this.obstacles = [];
        this.environmentEffects = [];
    }
    
    createSpecialZone(zoneData) {
        const zone = {
            ...zoneData,
            id: 'zone_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9),
            active: true,
            startTime: Date.now()
        };
        
        this.specialZones.push(zone);
        this.renderSpecialZone(zone);
        
        // 设置持续时间
        if (zone.duration) {
            setTimeout(() => {
                this.removeSpecialZone(zone.id);
            }, zone.duration);
        }
        
        console.log(`🌟 创建特殊区域: ${zone.type}`);
    }
    
    createObstacle(obstacleData) {
        const obstacle = {
            ...obstacleData,
            id: 'obstacle_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9),
            health: obstacleData.health || 100,
            maxHealth: obstacleData.health || 100
        };
        
        this.obstacles.push(obstacle);
        console.log('🧱 创建障碍物:', obstacle);
    }
    
    renderSpecialZone(zone) {
        // 禁用特殊区域渲染 - 这是造成红色圆圈的另一个源头
        return;
        /*
        // 这个方法将由游戏引擎调用来渲染特殊区域
        // 在实际实现中，这应该与游戏的渲染系统集成
        if (window.gameEngine && window.gameEngine.ctx) {
            const ctx = window.gameEngine.ctx;
            
            // 渲染区域效果
            ctx.save();
            ctx.globalAlpha = 0.3;
            
            if (zone.type === 'healing') {
                ctx.fillStyle = '#00ff00';
            } else if (zone.type === 'damage_boost') {
                ctx.fillStyle = '#ff4444';
            }
            
            ctx.beginPath();
            ctx.arc(zone.x, zone.y, zone.radius, 0, Math.PI * 2);
            ctx.fill();
            ctx.restore();
        }
        */
    }
    
    removeSpecialZone(zoneId) {
        this.specialZones = this.specialZones.filter(zone => zone.id !== zoneId);
        console.log(`❌ 移除特殊区域: ${zoneId}`);
    }
    
    // 检查玩家是否在特殊区域内
    checkPlayerInZones() {
        if (!window.player) return;
        
        this.specialZones.forEach(zone => {
            if (!zone.active) return;
            
            const distance = Math.sqrt(
                Math.pow(window.player.x - zone.x, 2) + 
                Math.pow(window.player.y - zone.y, 2)
            );
            
            if (distance <= zone.radius) {
                this.applyZoneEffect(zone);
            }
        });
    }
    
    applyZoneEffect(zone) {
        switch (zone.type) {
            case 'healing':
                if (window.player.health < window.player.maxHealth) {
                    window.player.health = Math.min(
                        window.player.maxHealth, 
                        window.player.health + 1
                    );
                    window.player.updateHealthUI();
                }
                break;
                
            case 'damage_boost':
                // 临时增加伤害
                if (window.player.currentWeapon && !window.player.currentWeapon.zoneBoostApplied) {
                    window.player.currentWeapon.damage *= 1.5;
                    window.player.currentWeapon.zoneBoostApplied = true;
                    
                    // 5秒后移除效果
                    setTimeout(() => {
                        if (window.player.currentWeapon) {
                            window.player.currentWeapon.damage /= 1.5;
                            window.player.currentWeapon.zoneBoostApplied = false;
                        }
                    }, 5000);
                }
                break;
        }
    }
    
    // 更新方法 - 由游戏循环调用
    update() {
        this.checkPlayerInZones();
        
        // 更新特殊区域
        this.specialZones.forEach(zone => {
            if (zone.duration && Date.now() - zone.startTime > zone.duration) {
                zone.active = false;
            }
        });
        
        // 清理非活跃区域
        this.specialZones = this.specialZones.filter(zone => zone.active);
    }
    
    // 渲染方法 - 由游戏渲染循环调用
    render(ctx) {
        // 渲染特殊区域
        this.specialZones.forEach(zone => {
            if (zone.active) {
                this.renderSpecialZone(zone);
            }
        });
        
        // 渲染障碍物
        this.obstacles.forEach(obstacle => {
            ctx.save();
            ctx.fillStyle = '#654321';
            ctx.fillRect(obstacle.x, obstacle.y, obstacle.width, obstacle.height);
            
            // 渲染生命条
            if (obstacle.health < obstacle.maxHealth) {
                ctx.fillStyle = '#ff0000';
                ctx.fillRect(obstacle.x, obstacle.y - 10, obstacle.width, 5);
                ctx.fillStyle = '#00ff00';
                ctx.fillRect(obstacle.x, obstacle.y - 10, 
                    obstacle.width * (obstacle.health / obstacle.maxHealth), 5);
            }
            
            ctx.restore();
        });
    }
    
    clearEnvironment() {
        this.specialZones = [];
        this.obstacles = [];
        this.environmentEffects = [];
    }
}

// 如果没有现有的 LevelManager，创建增强版；否则扩展现有的
if (typeof LevelManager === 'undefined') {
    window.LevelManager = LevelManagerEnhanced;
} else {
    // 扩展现有的 LevelManager
    window.LevelManagerEnhanced = LevelManagerEnhanced;
}

console.log('增强关卡系统已加载');